#include "head.h"

// up
int up(messenger_t* msg, int sock_fd)
{
    char hash[1024] = {0};
    // 得到文件名 调用 popen
    char* file = msg->args;
    while(*file++ != '&'); 
    sprintf(hash, "sha1sum %s", file);
    FILE* stream = popen(hash, "r");
    fread(hash, 1, sizeof(hash), stream);
    for(int i = 0;;++i)
    {
        if(hash[i] == ' ')
        {
            hash[i] = '\0';
            break;
        }
    }
    fclose(stream);

    struct stat file_stat;
    int file_fd = open(file, O_RDWR);
    fstat(file_fd, &file_stat);

    char cs[100] = {0};
    strcpy(cs, msg->args);
    bzero(msg->args, sizeof(messenger_t));

    sprintf(msg->args, "%s&%s&%ld", cs, hash, file_stat.st_size);
    // 现在的参数是 path & filename & hash & size

    
    //sleep(3);
    send(sock_fd, &msg, sizeof(msg), MSG_NOSIGNAL);
    printf("args: %s\n", msg->args);



    // 等待服务器回应
    int ret;
    recv(sock_fd, &ret, sizeof(int), 0);
    if(ret == 0)
    {
        printf("存在同名文件\n");
    }
    else if(ret == 1)
    {
        printf("秒传成功\n");
    }
    else if(ret == 2)
    {
        // 上传
        printf("上传成功\n");
        // sendfile(sock_fd, file_fd, NULL, file_stat->st_size);
    }
    else
        printf("未知错误\n");

    close(file_fd);
    return 0;
}